<?php

namespace july\julyadmin\builder\forms;

use july\julyadmin\builder\FormBase;

/**
 * 表单switch开关组件
 */
class SwitchBtn extends FormBase
{
    /**
     * 添加组件
     * @Author
     * @DateTime 2023-07-16T12:14:26+0800
     * @param    string                   $field 字段
     * @param    string                   $label 名称
     * @return this
     */
    public function __construct($field = '', $label = '')
    {
        $form                = new \stdClass();
        $form->type          = 'switch-btn';
        $form->field         = $field;
        $form->label         = $label;
        $form->help          = '';
        $form->tips          = ['tips' => '', 'direction' => 2, 'time' => 0, 'background' => '#000000'];
        $form->required      = false;
        $form->style         = '';
        $form->switchBtnText = ['开启', '关闭'];
        //内容
        $form->value   = '';
        $form->default = '';
        //要关联显示的表单组件列表
        $form->whenForms = [];
        //要关联显示的条件
        $form->whenWhere = '';
        $this->form      = $form;
        return $this;
    }

    /**
     * 设置style
     * @Author
     * @DateTime 2023-07-16T12:19:05+0800
     * @param    string                   $style 样式，直接写css
     * @return   this
     */
    public function style($style = '')
    {
        $this->form->style = $style;
        return $this;
    }

    /**
     * 设置开关开启和关闭文字
     * @Author   july
     * @DateTime 2023-09-05
     * @param    array     $val 开启和关闭文字['开启','关闭']
     * @return   this
     */
    public function switchBtnText($val = [])
    {
        if (!$val || !is_array($val) || count($val) < 2) {
            throw new \Exception("switchBtnText格式为：['开启','关闭']，第一个参数为开关开启时的文字，第二个参数为开关关闭时的文字");
        }

        $this->form->switchBtnText = $val;
        return $this;
    }

    /**
     * 设置颜色
     * @Author
     * @DateTime 2023-07-16T12:37:26+0800
     * @param    string                   $color 颜色英文 如blue
     * 支持blue蓝色,indigo靛蓝,purple紫色,pink粉红,red红色,orange橙色,yellow黄色,green绿色,cyan青色,brown棕色,gray灰色,dark黑色,teal灰色
     * @return  this
     */
    public function setColor($color = 'blue')
    {
        $this->form->color = $color;
        return $this;
    }

    /**
     * 关联显示指定组件
     * @Author
     * @DateTime 2023-07-16T12:43:21+0800
     * @param    string                   $where  只能是：一维数组,数字,字符串类型，如:'1'或者1或者[1,2]，如果为数组，将判断当前组件的值是否存在于数组中'注意：区分数据类型'
     * @param    form                     $form   要关联显示的下一个组件
     * @return   this
     */
    public function when($where = '', ...$form)
    {
        if (!is_array($where) && !is_numeric($where) && !is_string($where)) {
            throw new \Exception("第一个参数是显示条件，只能是：一维数组,数字,字符串类型，如:'1'或者1或者[1,2]，如果为数组，将判断当前组件的值是否存在于数组中'注意：区分数据类型'");
        }
        if (!is_array($form)) {
            throw new \Exception("第二个参数必须是july\julyadmin\builder\form");
        }
        $this->form->whenWhere = $where;
        $this->form->whenForms = $form;
        return $this;
    }

    /**
     * 渲染组件
     * @Author
     * @DateTime 2023-07-16T12:22:46+0800
     * @return   array
     */
    public function render($items_field = '')
    {
        if ($items_field) {
            $this->html        = '';
            $this->script      = '';
            $this->form->value = '';
        }
        $this->form->value = $this->form->default;
        if (isset($this->data[$this->form->field]) && $this->data[$this->form->field] !== "") {
            $this->form->value = $this->data[$this->form->field];
        }

        $required_html = $this->form->required && !$this->isView ? ' <font style="color:red;font-weight:bold;font-size:20px;vertical-align:-webkit-baseline-middle;">*</font>' : '';

        $this->html .= <<< EOT

        <div class="row ps-0 pe-0 ms-0 me-0 mt-3 mb-3 col-md-{$this->colWidth}">
            <label class="col-sm-{$this->labelWidth} col-form-label pe-2 col-form-label-sm text-sm-end text-md-end text-lg-end text-xl-end">
                {$this->form->label}
                {$required_html}
            </label>
EOT;
        $input_html = "";
        $color      = isset($this->form->color) && $this->form->color ? 'form-check-' . $this->form->color : '';
        $required   = $this->form->required ? 'required' : '';
        $checked    = $this->form->value ? 'checked' : '';
        $disabled   = $this->readonly ? 'disabled' : '';
        if (!$this->isView) {
            $input_html .= <<< EOT

            <div class="form-check form-switch">
                <input type="checkbox" role="switch" class="form-check-input {$color}" id="form-{$items_field}{$this->form->field}{$this->items_row_id_template_fun}" name="{$this->items_row_prefix}{$this->form->field}" value="1" {$required} {$checked} style="width:50px;height:20px;{$this->form->style}" {$disabled}/>
            </div>
EOT;
        } else {
            $input_html .= '<font class="d-flex align-items-center h-100">';
            $input_html .= $this->form->value ? $this->form->switchBtnText[0] : $this->form->switchBtnText[1];
            $input_html .= '</font>';
        }

        //处理help
        if ($this->form->help && !$this->isView) {
            $input_html .= <<<EOT

            <div class="form-help form-text">
                <i class="mdi mdi-information-outline"></i>
                <font>{$this->form->help}</font>
            </div>
EOT;
        }

        $this->html .= <<< EOT

            <div class="col-sm-{$this->inputWidth}">
                {$input_html}
            </div>
        </div>
EOT;

        $whenScript = '';
        $whenScript .= <<<EOT

        <script>
        $('input[name="{$this->items_row_prefix}{$this->form->field}"]').change(function(){

EOT;
        foreach ($this->form->whenForms as $form_k => $form_v) {
            //如果条件是一维数组
            if (is_array($this->form->whenWhere)) {
                $whereStr = json_encode($this->form->whenWhere, JSON_UNESCAPED_UNICODE);
                $whenScript .= <<<EOT

                if({$whereStr}.includes($('input[name="{$this->items_row_prefix}{$this->form->field}"]:checked').val())){
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().show();
                }else{
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().hide();
                }

EOT;
            }

            //如果是字符串
            if (is_string($this->form->whenWhere)) {
                $whenScript .= <<<EOT

                if('{$this->form->whenWhere}'==$('input[name="{$this->items_row_prefix}{$this->form->field}"]:checked').val()){
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().show();
                }else{
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().hide();
                }

EOT;
            }

            //如果是数字
            if (is_numeric($this->form->whenWhere)) {
                $whenScript .= <<<EOT

                if({$this->form->whenWhere}==$('input[name="{$this->items_row_prefix}{$this->form->field}"]:checked').val()){
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().show();
                }else{
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().hide();
                }

EOT;
            }
        }

        $whenScript .= <<<EOT

        });
        </script>

EOT;

        $whenScript .= <<<EOT

        <script>
        $(document).ready(function(e) {

EOT;
        foreach ($this->form->whenForms as $form_k => $form_v) {
            //如果条件是一维数组
            if (is_array($this->form->whenWhere)) {
                $whereStr = json_encode($this->form->whenWhere, JSON_UNESCAPED_UNICODE);
                $whenScript .= <<<EOT

                if({$whereStr}.includes($('input[name="{$this->items_row_prefix}{$this->form->field}"]:checked').val())){
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().show();
                }else{
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().hide();
                }

EOT;
            }

            //如果是字符串
            if (is_string($this->form->whenWhere)) {
                $whenScript .= <<<EOT

                if('{$this->form->whenWhere}'==$('input[name="{$this->items_row_prefix}{$this->form->field}"]:checked').val()){
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().show();
                }else{
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().hide();
                }

EOT;
            }

            //如果是数字
            if (is_numeric($this->form->whenWhere)) {
                $whenScript .= <<<EOT

                if({$this->form->whenWhere}==$('input[name="{$this->items_row_prefix}{$this->form->field}"]:checked').val()){
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().show();
                }else{
                    $('[name="{$this->items_row_prefix}{$form_v->form->field}"]').parent().parent().hide();
                }

EOT;
            }
        }

        $whenScript .= <<<EOT

        });
        </script>

EOT;
        if (!$this->form->whenWhere || !$this->form->whenForms) {
            $whenScript = '';
        }

        $result = ['html' => $this->html, 'script' => $this->script . $whenScript];
        return $result;
    }
}
